package com.rfid.web.controller.system;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.rfid.common.exception.BusinessException;
import com.rfid.common.utils.CacheUtils;
import com.rfid.common.utils.ShiroUtils;
import com.rfid.common.utils.StringUtils;
import com.rfid.common.utils.uuid.UUID;
import com.rfid.framework.web.service.CodeGenerateService;
import com.rfid.system.domain.*;
import com.rfid.system.service.ITCustomerInfoService;
import com.rfid.system.service.ITProductOrderTotalService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rfid.common.annotation.Log;
import com.rfid.common.enums.BusinessType;
import com.rfid.system.service.ITOrderTotalService;
import com.rfid.common.core.controller.BaseController;
import com.rfid.common.core.domain.AjaxResult;
import com.rfid.common.utils.poi.ExcelUtil;
import com.rfid.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 单据总Controller
 *
 * @author fangchen
 * @date 2020-12-24
 */
@Controller
@RequestMapping("/system/total")
public class TOrderTotalController extends BaseController {
    private String prefix = "system/total";

    @Autowired
    private ITOrderTotalService tOrderTotalService;

    @Autowired
    private ITCustomerInfoService tCustomerInfoService;

    @Autowired
    private CodeGenerateService codeGenerateService;

    @Autowired
    private ITProductOrderTotalService itProductOrderTotalService;

    @RequiresPermissions("system:total:view")
    @GetMapping()
    public String total() {
        return prefix + "/total";
    }

    /**
     * 查询单据总列表
     */
    @RequiresPermissions("system:total:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TOrderTotal tOrderTotal) {
        startPage();
        List<TOrderTotal> list = tOrderTotalService.selectTOrderTotalList(tOrderTotal);
        if(CollectionUtils.isNotEmpty(list)){
            list.forEach(total->{
                Long customerId=total.getCustomerId();
                TCustomerInfo tCustomerInfo=tCustomerInfoService.selectTCustomerInfoById(customerId);
                total.setCustomerName(tCustomerInfo.getUserName());
            });
        }
        return getDataTable(list);
    }

    /**
     * 导出单据总列表
     */
    @RequiresPermissions("system:total:export")
    @Log(title = "单据总", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TOrderTotal tOrderTotal) {
        List<TOrderTotal> list = tOrderTotalService.selectTOrderTotalList(tOrderTotal);
        ExcelUtil<TOrderTotal> util = new ExcelUtil<TOrderTotal>(TOrderTotal.class);
        return util.exportExcel(list, "total");
    }

    /**
     * 新增单据总
     */
    @GetMapping("/add")
    public String add( ModelMap mmap) {
        UUID uuid= UUID.randomUUID();
        Object uuids=CacheUtils.get("uuid");
        if(uuids==null){
            uuids=uuid.getLeastSignificantBits()+"";
        }
        CacheUtils.put("uuid",uuids);
        mmap.put("uuids", uuids);
        return prefix + "/add";
    }

    /**
     * 新增保存单据总
     */
    @RequiresPermissions("system:total:add")
    @Log(title = "单据总表", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TOrderTotal tOrderTotal) {
        TOrderTotal lastData=tOrderTotalService.getLastData();
        String orderNo="";
        if(lastData!=null){
            orderNo=codeGenerateService.generateCode("ORDER_TOTAL_CODE_RULE",lastData.getOrderNo(),lastData);
        }else{
            orderNo=codeGenerateService.generateCode("ORDER_TOTAL_CODE_RULE","",lastData);
        }

        if(StringUtils.isEmpty(orderNo)){
            throw new BusinessException("生成单据编码不能为空");
        }
        TOrderTotal queryCus=new TOrderTotal();
        Map<String,Object> map= Maps.newLinkedHashMap();
        queryCus.setOrderNo(orderNo);
        map.put("beginOrderDate","");
        map.put("endOrderDate","");
        queryCus.setParams(map);
        List<TOrderTotal> list=tOrderTotalService.selectTOrderTotalList(queryCus);
        if(CollectionUtils.isNotEmpty(list)){
            throw new BusinessException("生成单据编码重复");
        }
        tOrderTotal.setOrderNo(orderNo);
        tOrderTotal.setCreateBy(ShiroUtils.getLoginName());
        tOrderTotal.setOrderDate(new Date());
        tOrderTotal.setUpdateBy(ShiroUtils.getLoginName());
        tOrderTotal.setCreateTime(new Date());
        tOrderTotal.setUpdateTime(new Date());
        String remark= CacheUtils.get("uuid").toString();
        int i=tOrderTotalService.insertTOrderTotal(tOrderTotal);
        //更新关联表的成品id
        String uuid=CacheUtils.get("uuid")==null?"":CacheUtils.get("uuid")+"";
        TProductOrderTotal tProductOrderTotal=new TProductOrderTotal();
        tProductOrderTotal.setRemark(uuid);
        List<TProductOrderTotal> tProductOrderTotals=itProductOrderTotalService.selectTProductOrderTotalList(tProductOrderTotal);
        tProductOrderTotals.stream().forEach(t->{
            t.setOrderTotalId(tOrderTotal.getId());
            itProductOrderTotalService.updateTProductOrderTotal(t);
        });
        if(!StringUtils.isEmpty(remark)){
            CacheUtils.remove("uuid");
        };
        return toAjax(i);
    }

    /**
     * 修改单据总表
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        TOrderTotal tOrderTotal = tOrderTotalService.selectTOrderTotalById(id);
        Long customerId=tOrderTotal.getCustomerId();
        TCustomerInfo tCustomerInfo=tCustomerInfoService.selectTCustomerInfoById(customerId);
        tOrderTotal.setCustomerName(tCustomerInfo.getUserName());
        UUID uuid= UUID.randomUUID();
        Object uuids=CacheUtils.get("uuid");
        if(uuids==null){
            uuids=uuid.getLeastSignificantBits()+"";
        }
        CacheUtils.put("uuid",uuids);
        mmap.put("tOrderTotal", tOrderTotal);
        mmap.put("uuids", uuids);
        return prefix + "/edit";
    }

    /**
     * 修改保存单据总
     */
    @RequiresPermissions("system:total:edit")
    @Log(title = "单据总", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TOrderTotal tOrderTotal) {
        String remark= CacheUtils.get("uuid").toString();
        //更新关联表的成品id
        String uuid=CacheUtils.get("uuid")==null?"":CacheUtils.get("uuid")+"";
        TProductOrderTotal tProductOrderTotal=new TProductOrderTotal();
        tProductOrderTotal.setRemark(uuid);
        List<TProductOrderTotal> tProductOrderTotals=itProductOrderTotalService.selectTProductOrderTotalList(tProductOrderTotal);
        tProductOrderTotals.stream().forEach(t->{
            t.setOrderTotalId(tOrderTotal.getId());
            itProductOrderTotalService.updateTProductOrderTotal(t);
        });
        if(!StringUtils.isEmpty(remark)){
            CacheUtils.remove("uuid");
        };
        return toAjax(tOrderTotalService.updateTOrderTotal(tOrderTotal));
    }

    /**
     * 删除单据总
     */
    @RequiresPermissions("system:total:remove")
    @Log(title = "单据总", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(tOrderTotalService.deleteTOrderTotalByIds(ids));
    }

    /**
     * @Author fangchen
     * @Description //查看单据总表数据
     * @Date 10:04 2020/12/29
     * @Param [orderId, mmap]
     * @return java.lang.String
     **/
    @RequiresPermissions("system:total:detail")
    @GetMapping("/detail/{orderId}")
    public String detail(@PathVariable("orderId") Long orderId, ModelMap mmap) {
        TOrderTotal tOrderTotal = tOrderTotalService.selectTOrderTotalById(orderId);
        mmap.put("tOrderTotal", tOrderTotal);
        return prefix + "/detail";
    }

    @RequiresPermissions("system:total:import")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<TOrderTotal> util = new ExcelUtil<TOrderTotal>(TOrderTotal.class);
        return util.importTemplateExcel("单据数据");
    }

    /**
     * 导入单据数据
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "单据管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:total:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<TOrderTotal> util = new ExcelUtil<TOrderTotal>(TOrderTotal.class);
        List<TOrderTotal> cusList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message = tOrderTotalService.importUser(cusList, updateSupport, operName);
        return AjaxResult.success(message);
    }
}
